package cn.conac.rc.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.conac.rc.entity.DicTreeEntity;
import cn.conac.rc.framework.service.GenericService;
import cn.conac.rc.repository.DicTreeRepository;

/**
 * DicTreeService类
 *
 * @author serviceCreator
 * @date 2016-12-08
 * @version 1.0
 */
@Service
public class DicTreeService extends GenericService<DicTreeEntity, Integer> {

	@Autowired
	private DicTreeRepository dicTreeRepository;

	/**
	 * 根据baseId查询该机构的所有内设机构信息(并按照内设顺序号升序排序)
	 * @param baseId
	 * @param mapTree
	 * @return 一级内设机构List
	 */
	public List<DicTreeEntity> findMapTree(Map<String,Object> mapTree) {
		mapTree.put("id", 0);
		mapTree.put("code", 0);
		mapTree.put("name", dicTreeRepository.findDicTreeRootName().getName());

		List<Map<String, Object>> childDicTreeList= new ArrayList<Map<String, Object>>();
		Map<String, Object> dicTreetMap = null;
		List<DicTreeEntity> dicTreeList  = dicTreeRepository.findByPidOrderByOrderNumAsc(0);
		for(DicTreeEntity dicTreeEntity: dicTreeList){
			dicTreetMap = new HashMap<String, Object>();
			dicTreetMap.put("id",dicTreeEntity.getId());
			dicTreetMap.put("name",dicTreeEntity.getName());
			dicTreetMap.put("code",dicTreeEntity.getCode());
			// 递归调用枝干节点
			if(new Integer(0).equals(dicTreeEntity.getLeaf())){
				recursiveDicTreeTree(dicTreeEntity.getId(), dicTreetMap);
			}
		    childDicTreeList.add(dicTreetMap);
		}
		mapTree.put("children",childDicTreeList);
		return dicTreeList;
	}
	
	/**
	 * 根据主键ID递归查询level2一下的内设机构信息
	 * @param id
	 * @param map
	 * @return 返回以该ID为父的内设机构List
	 */
	public  List<DicTreeEntity> recursiveDicTreeTree(Integer id, Map<String,Object> map) {
	     List<DicTreeEntity> dicTreeList = dicTreeRepository.findByPidOrderByOrderNumAsc(id);
	     List<Map<String, Object>> childDicTreeList= new ArrayList<Map<String, Object>>();
	     Map<String, Object> dicTreeMap = null;
	     for(DicTreeEntity dicTreeEntity : dicTreeList){
	    	 dicTreeMap = new HashMap<String, Object>();
			 dicTreeMap.put("id",dicTreeEntity.getId());
			 dicTreeMap.put("name",dicTreeEntity.getName());
			 dicTreeMap.put("code",dicTreeEntity.getCode());
			 // 递归调用枝干节点
			 if(new Integer(0).equals(dicTreeEntity.getLeaf())){
				 recursiveDicTreeTree(dicTreeEntity.getId(),dicTreeMap);
			 }
	    	 childDicTreeList.add(dicTreeMap);
	     }
	     map.put("children",childDicTreeList);
	     return dicTreeList;
	}

}
